<template>
  <div class="resume-template-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">简历模板管理</span>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            添加模板
          </el-button>
        </div>
      </template>

      <!-- 模板列表 -->
      <div class="template-content" v-loading="loading">
        <div v-if="templateList.length === 0" class="empty-state">
          <el-empty description="暂无模板">
            <el-button type="primary" @click="showCreateDialog = true">
              添加第一个模板
            </el-button>
          </el-empty>
        </div>

        <div v-else class="template-grid">
          <div
            v-for="template in templateList"
            :key="template.id"
            class="template-card"
          >
            <div class="template-preview">
              <img 
                v-if="template.preview_image" 
                :src="template.preview_image" 
                :alt="template.name"
                class="preview-image"
              />
              <div v-else class="preview-placeholder">
                <el-icon><Document /></el-icon>
                <span>暂无预览</span>
              </div>
            </div>

            <div class="template-info">
              <div class="template-header">
                <h4 class="template-name">{{ template.name }}</h4>
                <el-tag 
                  :type="template.is_active ? 'success' : 'danger'"
                  size="small"
                >
                  {{ template.is_active ? '启用' : '禁用' }}
                </el-tag>
              </div>
              
              <p class="template-desc">{{ template.description || '暂无描述' }}</p>
              
              <div class="template-meta">
                <span class="meta-item">创建时间：{{ formatTime(template.created_at) }}</span>
                <span class="meta-item">更新时间：{{ formatTime(template.updated_at) }}</span>
              </div>

              <div class="template-actions">
                <el-button 
                  type="text" 
                  size="small"
                  @click="handleEdit(template)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="text" 
                  size="small"
                  @click="handleDownload(template)"
                  v-if="template.template_file"
                >
                  下载
                </el-button>
                <el-button 
                  type="text" 
                  size="small"
                  @click="handleToggleStatus(template)"
                >
                  {{ template.is_active ? '禁用' : '启用' }}
                </el-button>
                <el-button 
                  type="text" 
                  size="small"
                  @click="handleDelete(template)"
                  style="color: var(--color-danger)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 创建/编辑模板对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingTemplate ? '编辑模板' : '添加模板'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入模板名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入模板描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="模板文件" prop="template_file">
          <el-upload
            ref="templateUploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".doc,.docx,.pdf"
            :on-change="handleTemplateFileChange"
            :on-remove="handleTemplateFileRemove"
            :before-upload="beforeTemplateUpload"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择模板文件
            </el-button>
            <template #tip>
              <div class="upload-tip">
                支持 DOC、DOCX、PDF 格式，文件大小不超过 20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="预览图片" prop="preview_image">
          <el-upload
            ref="previewUploadRef"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handlePreviewImageChange"
            :before-upload="beforePreviewUpload"
          >
            <div class="preview-uploader">
              <img v-if="form.preview_image" :src="previewImageUrl" class="preview-img" />
              <div v-else class="preview-placeholder">
                <el-icon><Plus /></el-icon>
                <div class="text">上传预览图</div>
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="form.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSave"
            :loading="saving"
          >
            {{ editingTemplate ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import { resumeTemplateApi, type ResumeTemplate } from '@/api/resume'
import { formatTime } from '@/utils/format'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showCreateDialog = ref(false)
const templateList = ref<ResumeTemplate[]>([])
const editingTemplate = ref<ResumeTemplate | null>(null)

// 表单引用
const formRef = ref<FormInstance>()
const templateUploadRef = ref()
const previewUploadRef = ref()

// 表单数据
const form = reactive({
  name: '',
  description: '',
  template_file: null as File | null,
  preview_image: null as File | null,
  is_active: true
})

// 预览图片URL
const previewImageUrl = computed(() => {
  if (form.preview_image) {
    return URL.createObjectURL(form.preview_image)
  }
  return ''
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 100, message: '名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  template_file: [
    { required: true, message: '请选择模板文件', trigger: 'change' }
  ]
}

// 获取模板列表
const fetchTemplateList = async () => {
  loading.value = true
  try {
    const response = await resumeTemplateApi.getTemplateList()
    const data = response.data || response
    templateList.value = data.results || data || []
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 处理模板文件变化
const handleTemplateFileChange = (file: UploadFile) => {
  form.template_file = file.raw || null
}

// 处理模板文件移除
const handleTemplateFileRemove = () => {
  form.template_file = null
}

// 模板文件上传前验证
const beforeTemplateUpload = (file: File) => {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const isValidType = allowedTypes.includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 20

  if (!isValidType) {
    ElMessage.error('只支持 DOC、DOCX、PDF 格式的文件')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 20MB')
    return false
  }

  return true
}

// 处理预览图片变化
const handlePreviewImageChange = (file: UploadFile) => {
  form.preview_image = file.raw || null
}

// 预览图片上传前验证
const beforePreviewUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isValidSize = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 5MB')
    return false
  }
  return true
}

// 处理编辑
const handleEdit = (template: ResumeTemplate) => {
  editingTemplate.value = template
  form.name = template.name
  form.description = template.description || ''
  form.is_active = template.is_active
  form.template_file = null
  form.preview_image = null
  showCreateDialog.value = true
}

// 处理下载
const handleDownload = (template: ResumeTemplate) => {
  if (template.template_file) {
    window.open(template.template_file, '_blank')
  }
}

// 处理状态切换
const handleToggleStatus = async (template: ResumeTemplate) => {
  try {
    await resumeTemplateApi.updateTemplate(template.id, {
      is_active: !template.is_active
    })
    template.is_active = !template.is_active
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 处理删除
const handleDelete = async (template: ResumeTemplate) => {
  try {
    await ElMessageBox.confirm('确定要删除这个模板吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await resumeTemplateApi.deleteTemplate(template.id)
    ElMessage.success('删除成功')
    fetchTemplateList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    saving.value = true

    const formData = new FormData()
    formData.append('name', form.name)
    formData.append('description', form.description)
    formData.append('is_active', form.is_active.toString())
    
    if (form.template_file) {
      formData.append('template_file', form.template_file)
    }
    
    if (form.preview_image) {
      formData.append('preview_image', form.preview_image)
    }

    if (editingTemplate.value) {
      // 更新
      await resumeTemplateApi.updateTemplate(editingTemplate.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 创建
      await resumeTemplateApi.createTemplate(formData)
      ElMessage.success('创建成功')
    }

    handleDialogClose()
    fetchTemplateList()

  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 处理对话框关闭
const handleDialogClose = () => {
  showCreateDialog.value = false
  editingTemplate.value = null
  formRef.value?.resetFields()
  form.name = ''
  form.description = ''
  form.template_file = null
  form.preview_image = null
  form.is_active = true
  templateUploadRef.value?.clearFiles()
  previewUploadRef.value?.clearFiles()
}

// 生命周期
onMounted(() => {
  fetchTemplateList()
})
</script>

<style lang="scss" scoped>
.resume-template-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  .template-content {
    .empty-state {
      padding: 60px 0;
      text-align: center;
    }

    .template-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 20px;

      .template-card {
        border: 1px solid var(--border-color-light);
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .template-preview {
          height: 200px;
          background: var(--fill-color-extra-light);
          display: flex;
          align-items: center;
          justify-content: center;

          .preview-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .preview-placeholder {
            text-align: center;
            color: var(--text-color-placeholder);

            .el-icon {
              font-size: 48px;
              margin-bottom: 8px;
            }
          }
        }

        .template-info {
          padding: 16px;

          .template-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .template-name {
              font-size: 16px;
              font-weight: 600;
              color: var(--text-color-primary);
              margin: 0;
            }
          }

          .template-desc {
            color: var(--text-color-secondary);
            font-size: 14px;
            line-height: 1.4;
            margin: 0 0 12px 0;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .template-meta {
            margin-bottom: 16px;

            .meta-item {
              display: block;
              font-size: 12px;
              color: var(--text-color-placeholder);
              margin-bottom: 4px;
            }
          }

          .template-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
          }
        }
      }
    }
  }

  .upload-tip {
    font-size: 12px;
    color: var(--text-color-placeholder);
    margin-top: 4px;
  }

  .preview-uploader {
    width: 120px;
    height: 120px;
    border: 2px dashed var(--border-color-light);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--color-primary);
    }

    .preview-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 6px;
    }

    .preview-placeholder {
      text-align: center;
      color: var(--text-color-placeholder);

      .el-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }

      .text {
        font-size: 14px;
      }
    }
  }
}
</style>
